<?php

namespace App\Http\Controllers\Admin;

use App\Http\Models\User;
use Egulias\EmailValidator\Exception\AtextAfterCFWS;
use Illuminate\Foundation\Auth\AuthenticatesUsers;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Auth;
use App\Http\Controllers\Controller;
use Illuminate\Support\Facades\Route;
use Spatie\Permission\Models\Permission;
use Spatie\Permission\Models\Role;

class AuthController extends Controller
{
    use AuthenticatesUsers;
    /**
     * Create a new AuthController instance.
     *
     * @return void
     */
    public function __construct(Request $request)
    {
        // $this->middleware('auth:api', ['except' => ['login']]);
    }

    /**
     * Get a JWT via given credentials.
     *
     * @return \Illuminate\Http\JsonResponse
     */
    public function login()
    {
        // 这里修改需要验证的字段
        $credentials = request(['username', 'password']);

        if (! $token = auth()->attempt($credentials)) {
            return $this->respondWithData(1002, [], '未授权');
        }

        $data=['access_token'=>$token,'user'=>auth()->user()];

        return  respondWithData(0, $data, '登录成功');
    }

    /**
     * Get the authenticated User.
     *
     * @return \Illuminate\Http\JsonResponse
     */
    public function me()
    {
        return response()->json(auth()->user());
    }

    /**
     * Log the user out (Invalidate the token).
     *
     * @return \Illuminate\Http\JsonResponse
     */
    public function logout()
    {
        auth()->logout();
        return respondWithData(0, [], '退出成功');
    }

    /**
     * Refresh a token.
     *
     * @return \Illuminate\Http\JsonResponse
     */
    public function refresh()
    {
        $data=['refresh_token'=>auth()->refresh()];
        return respondWithData(0, $data, 'ok');
    }

    /**
     * Get the token array structure.
     *
     * @param  string $token
     *
     * @return \Illuminate\Http\JsonResponse
     */
    protected function respondWithToken($token)
    {
        return response()->json([
            'access_token' => $token,
            'token_type' => 'bearer',
            'expires_in' => auth()->factory()->getTTL() * 60
        ]);
    }

    protected function respondWithData($code, $data, $msg)
    {
        return response()->json(['data'=>$data,'code'=>$code,'msg'=>$msg]);
    }
}
